<template>
  <div>
    <TablePaging :tableItem="tableItem" :operationItem="operationItem"/>
  </div>
</template>
<script setup>
import TablePaging from '@/views/common/component/table-paging'
import {onMounted, ref} from 'vue'
import {operationItem, tableItem} from './const.js'
import {ElMessage} from 'element-plus'
import {useRouter} from 'vue-router'
import {delArticleCatalog, publishArticleCatalog} from '@/api/article/catalog'

const {proxy} = getCurrentInstance();
const router = useRouter()

function initTableItem() {
  let menuArray = operationItem.menuArray
  let addMenu = menuArray.find(item => item.code === 'add')
  addMenu.handle = goAdd

  let delMenu = menuArray.find(item => item.code === 'del')
  delMenu.handle = delBatch

  let btnArray = tableItem.btnArray
  let detailBtn = btnArray.find(item => item.code === 'detail')
  detailBtn.handle = goDetail

  let editBtn = btnArray.find(item => item.code === 'edit')
  editBtn.handle = goEdit

  let publishedBtn = btnArray.find(item => item.code === 'published')
  publishedBtn.handle = (row) => {
    publish(row, true)
  }
  let unpublishedBtn = btnArray.find(item => item.code === 'unpublished')
  unpublishedBtn.handle = (row) => {
    publish(row, false)
  }
}

function goDetail(row) {
  router.push({
    path: '/modules/article/catalog/detail',
    query: {id: row.id}
  })
}

function goAdd() {
  router.push({
    path: '/modules/article/catalog/save',
    query: {type: 'add'}
  })
}

function goEdit(row) {
  router.push({
    path: '/modules/article/catalog/save',
    query: {id: row.id, type: 'edit'}
  })
}

const selectedRow = ref([])
tableItem.selectChange = (row) => {
  //构建需要删除的id列表
  selectedRow.value = row.map((item) => {
    return item.id
  })
}

//批量删除
function delBatch() {
  if (selectedRow.value.length < 1) {
    return ElMessage.warning('请先选择内容');
  }
  proxy.$modal.confirm('确认要删除选中的内容吗?').then(function () {
    return delArticleCatalog(selectedRow.value);
  }).then(res => {
    tableItem.pageInfo.paging()
    ElMessage.success(res.msg);
  }).catch(() => {
  });
}

//上下架
function publish(row, isPublish) {
  let requestData = {id: row.id}
  requestData.publishedFlag = isPublish ? 1 : 0
  publishArticleCatalog(requestData).then((res) => {
    if (res.code === 200) {
      tableItem.pageInfo.paging()
      ElMessage.success('操作成功');
    }
  })
}

onMounted(() => {
  initTableItem()
})
</script>

<style></style>
